package com.szgz.platform.controller;

import com.szgz.platform.enums.EnvTypeEnum;
import com.szgz.platform.request.ResourceEnvironmentRequest;
import com.szgz.platform.result.ApiResponse;
import com.szgz.platform.result.ResourceEnvironmentResult;
import com.szgz.platform.service.ResourceEnvironmentService;
import com.szgz.platform.service.TeacherEnvironmentService;
import jakarta.annotation.Resource;
import jakarta.ws.rs.GET;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资源环境管理Controller
 * 提供资源环境的创建、查询、管理等接口
 */
@RestController
@RequestMapping("/api/resource-environments")
@CrossOrigin(origins = "*")
public class ResourceEnvironmentController {

    private static final Logger logger = LoggerFactory.getLogger(ResourceEnvironmentController.class);

    @Resource
    private ResourceEnvironmentService resourceEnvironmentService;


    /**
     * 创建资源环境
     * 接收资源环境配置参数，进行验证和处理，但不保存到数据库
     *
     * @param request 资源环境创建请求参数
     * @return 创建结果
     */
    @PostMapping("/create")
    public ApiResponse<List<ResourceEnvironmentResult>> createResourceEnvironment(@Valid @RequestBody ResourceEnvironmentRequest request) {
        try {
            logger.info("收到创建资源环境请求: {}", request);

            // 参数验证
            if (request.getResourceType() == null || request.getResourceType().trim().isEmpty()) {
                return ApiResponse.fail(400, "资源类型不能为空");
            }

            if (request.getEnvironmentTypes().isEmpty()) {
                return ApiResponse.fail(400, "环境类型不能为空");
            }

            if (request.getSystemEnvironment() == null || request.getSystemEnvironment().trim().isEmpty()) {
                return ApiResponse.fail(400, "系统环境不能为空");
            }


//            if (request.getCpu() == null || request.getCpu() <= 0) {
//                return ApiResponse.fail(400, "CPU核心数必须大于0");
//            }
//
//            if (request.getMemory() == null || request.getMemory() <= 0) {
//                return ApiResponse.fail(400, "内存大小必须大于0");
//            }
//
//            if (request.getDisk() == null || request.getDisk() <= 0) {
//                return ApiResponse.fail(400, "硬盘大小必须大于0");
//            }
//
//            if (request.getMachineCount() == null || request.getMachineCount() <= 0) {
//                return ApiResponse.fail(400, "机器数量必须大于0");
//            }

            for (String environmentType : request.getEnvironmentTypes()) {
                EnvTypeEnum.getByType(environmentType);
            }


            // 模拟资源环境创建过程

            List<ResourceEnvironmentResult> resourceEnvironmentResults = resourceEnvironmentService.createResourceEnvironment(request);

            return ApiResponse.success("资源环境创建请求已成功提交", resourceEnvironmentResults);

        } catch (Exception e) {
            logger.error("创建资源环境时发生错误", e);
            return ApiResponse.fail(500, "创建资源环境时发生内部错误: " + e.getMessage());
        }
    }

    /**
     * 删除资源环境
     */
    @GetMapping("/delete")
    public ApiResponse<String> deleteResourceEnvironment(@RequestParam String resourceEnvironmentId) {
        return resourceEnvironmentService.deleteResourceEnvironment(resourceEnvironmentId);
    }

    /**
     * 查询资源环境创建状态
     *
     * @param requestId 请求ID
     * @return 状态信息
     */
    @GetMapping("/status/{requestId}")
    public ApiResponse<Map<String, Object>> getResourceEnvironmentStatus(@PathVariable String requestId) {
        try {
            logger.info("查询资源环境状态，请求ID: {}", requestId);

            // 模拟状态查询结果
            Map<String, Object> statusInfo = new HashMap<>();
            statusInfo.put("requestId", requestId);
            statusInfo.put("status", "COMPLETED");
            statusInfo.put("progress", 100);
            statusInfo.put("message", "资源环境创建完成");
            statusInfo.put("completionTime", System.currentTimeMillis());

            return ApiResponse.success(statusInfo);

        } catch (Exception e) {
            logger.error("查询资源环境状态时发生错误", e);
            return ApiResponse.fail(500, "查询状态时发生内部错误: " + e.getMessage());
        }
    }

    /**
     * 获取支持的资源类型列表
     *
     * @return 资源类型列表
     */
    @GetMapping("/resource-types")
    public ApiResponse<Map<String, Object>> getSupportedResourceTypes() {
        try {
            Map<String, Object> resourceTypes = new HashMap<>();
            resourceTypes.put("virtualMachine", "虚拟机");
            resourceTypes.put("container", "容器");
            resourceTypes.put("bareMetal", "裸金属");

            return ApiResponse.success(resourceTypes);

        } catch (Exception e) {
            logger.error("获取资源类型列表时发生错误", e);
            return ApiResponse.fail(500, "获取资源类型列表时发生内部错误: " + e.getMessage());
        }
    }

    /**
     * 获取支持的环境类型列表
     *
     * @return 环境类型列表
     */
    @GetMapping("/environment-types")
    public ApiResponse<Map<String, Object>> getSupportedEnvironmentTypes() {
        try {
            Map<String, Object> environmentTypes = new HashMap<>();
            environmentTypes.put("MySQL", "MySQL数据库");
            environmentTypes.put("Redis", "Redis缓存");
            environmentTypes.put("MongoDB", "MongoDB数据库");
            environmentTypes.put("PostgreSQL", "PostgreSQL数据库");
            environmentTypes.put("Elasticsearch", "Elasticsearch搜索引擎");
            environmentTypes.put("Kafka", "Kafka消息队列");
            environmentTypes.put("Nginx", "Nginx Web服务器");
            environmentTypes.put("Tomcat", "Tomcat应用服务器");
            environmentTypes.put("Docker", "Docker容器环境");
            environmentTypes.put("Kubernetes", "Kubernetes集群");

            return ApiResponse.success(environmentTypes);

        } catch (Exception e) {
            logger.error("获取环境类型列表时发生错误", e);
            return ApiResponse.fail(500, "获取环境类型列表时发生内部错误: " + e.getMessage());
        }
    }

    /**
     * 获取支持的系统环境列表
     *
     * @return 系统环境列表
     */
    @GetMapping("/system-environments")
    public ApiResponse<Map<String, Object>> getSupportedSystemEnvironments() {
        try {
            Map<String, Object> systemEnvironments = new HashMap<>();
            systemEnvironments.put("CentOS", "CentOS Linux");
            systemEnvironments.put("Ubuntu", "Ubuntu Linux");
            systemEnvironments.put("Debian", "Debian Linux");
            systemEnvironments.put("RedHat", "Red Hat Enterprise Linux");
            systemEnvironments.put("Windows", "Windows Server");
            systemEnvironments.put("Alpine", "Alpine Linux");

            return ApiResponse.success(systemEnvironments);

        } catch (Exception e) {
            logger.error("获取系统环境列表时发生错误", e);
            return ApiResponse.fail(500, "获取系统环境列表时发生内部错误: " + e.getMessage());
        }
    }

    /**
     * 生成请求ID
     *
     * @return 请求ID
     */
    private String generateRequestId() {
        return "REQ_" + System.currentTimeMillis() + "_" + (int) (Math.random() * 1000);
    }
} 